package nioTest.com.io;

import org.bson.ByteBuf;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOClient2 {

    private final static InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 10280);
    private static SocketChannel socketChannel;
    private static Selector selector;

    public static void main(String[] args) throws Exception {

        socketChannel = SocketChannel.open(serverAddress);
        socketChannel.configureBlocking(false);
        selector = Selector.open();
        System.out.println(selector.isOpen());
        socketChannel.register(selector, SelectionKey.OP_READ);

        new Thread(() -> {
            readMsg();
        }).start();

        sendMsg();


        System.out.println("程序结束");
    }

    public static void sendMsg() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String s = "";
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (s.equals("stop")) {
                System.exit(-1);
            }
            try {
                socketChannel.write(ByteBuffer.wrap(s.getBytes()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void readMsg() {
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        while (true) {
            try {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey next = iterator.next();
                    System.out.println(next.interestOps());
                    if (next.isReadable()) {
//                        int msgLength = 0;
                        readBuffer.clear();
                        while (true) {
                            int read = socketChannel.read(readBuffer);
//                            if (read == -1) {
                                String receiveMsg = new String(readBuffer.array(), 0, read);
                                System.out.println(receiveMsg);
                                break;
//                            }
//                            msgLength += read;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
